// import axios from 'axios';
import { ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-message.css";
import { useUserStore } from "@/stores/userStore";
import router from "@/router";
import axios from 'axios';

// 创建axios实例
const request = axios.create({
  baseURL: '/api',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// axios请求拦截器
request.interceptors.request.use(
 (config) => {
    // 1.从pinia获取token数据
    const userStore = useUserStore();
    // 2.按照后端的要求拼接token数据
    const token = userStore.userInfo.token;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  e => Promise.reject(e)
)

// axios响应拦截器
request.interceptors.response.use(
  (res) => res.data,
  (e) => {
    const userStore = useUserStore();
    // 统一的错误提示
    if (e.response && e.response.data && e.response.data.message) {
      ElMessage({
        type: "warning",
        message: e.response.data.message,
      });
      // 401token处理
      // 1.清除本地用户数据
      // 2.跳转到登录页
      if (e.response.status === 401) {
        userStore.clearUserInfo();
        router.push('/login');
      }
    } else {
      ElMessage({
        type: "error",
        message: '网络请求失败，请稍后重试',
      });
    }
    return Promise.reject(e);
  }
)

export default request